package io.renren.modules.admin.controller;

import ch.qos.logback.core.net.SyslogOutputStream;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.renren.common.utils.Constant;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.common.utils.ShiroUtils;
import io.renren.modules.admin.entity.PhoneEntity;
import io.renren.modules.admin.entity.WarmUpEntity;
import io.renren.modules.admin.entity.vo.DevHttpJsonVo;
import io.renren.modules.admin.entity.vo.PhoneEntityVo;
import io.renren.modules.admin.entity.vo.SendTaskVo;
import io.renren.modules.admin.entity.vo.TaskReqVo;
import io.renren.modules.admin.service.AccountUpService;
import io.renren.modules.admin.service.ManagerWorkService;
import io.renren.modules.admin.service.PhoneService;
import io.renren.modules.admin.service.WarmUpService;
import io.renren.modules.app.interceptor.AuthorizationInterceptor;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author fangzq
 * @email canglx1996@163.com
 * @date 2020-12-01 16:06:19
 */
@RestController
@RequestMapping("admin/phoneback")
public class PhoneControllerback {
    @Autowired
    private PhoneService phoneService;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private WarmUpService warmUpService;
    @Autowired
    private ManagerWorkService managerWorkService;
    @Autowired
    private AccountUpService accountUpService;
    @Autowired
    private AuthorizationInterceptor authorizationInterceptor;

    private static List<PhoneEntityVo> phoneList = new ArrayList<>();
    static {
        phoneList.clear();
    }


    /**
     * 手机列表停止
     */
    @RequestMapping("shopTask")
    public R shopTask(@RequestBody HashMap<String, String> map1){
        // ①通过手机id 停止它的任务

        String id = map1.get("id");
        long l = Long.parseLong(id);
        // ②调用手机异常接口post
        Long userId = ShiroUtils.getUserId();
        if (userId == null) {
            return R.error("登陆信息出错，请重新登陆");
        }

        String url = "http://dou.shciyun.com/open/common/device/exception";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpMethod method = HttpMethod.POST;
        MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
        map.add("deviceId", id);
        map.add("userId",userId.toString());

        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
        ResponseEntity<DevHttpJsonVo> response = this.restTemplate.exchange( url,method, request , DevHttpJsonVo.class );
        // https://element.eleme.cn/#/zh-CN/component/select#select-attributes
        // TODO 判断状态


        return R.ok();
    }









    /**
     * 获取状态空闲的手机编号集合
     */
    public List<String> getFreePhoneNumList(int num, Long userId) {

        ResponseEntity<String> results = this.restTemplate.exchange("http://dou.shciyun.com/open/common/device/list?userId=" + userId, HttpMethod.GET, null, String.class);
        String json = results.getBody();
        DevHttpJsonVo devHttpJsonVo = JSON.parseObject(json.toString(), DevHttpJsonVo.class);
        JSONObject data1 = devHttpJsonVo.getData();
        JSONArray devices = data1.getJSONArray("devices");
        String js = JSONObject.toJSONString(devices);

        List<PhoneEntityVo> phoneEntityVos = new ArrayList<>();
        devices.forEach(item -> {
            PhoneEntityVo phoneEntityVo = JSONObject.toJavaObject((JSONObject) item, PhoneEntityVo.class);
            phoneEntityVos.add(phoneEntityVo);
            phoneList.add(phoneEntityVo);
        });
        if (phoneEntityVos == null) {
            return null;
        }
        List<String> free = new ArrayList<>();
        for (int i = 0; i < phoneEntityVos.size(); i++) {
            if (phoneEntityVos.get(i).getStatus() == 1 && phoneEntityVos.get(i).getTask() == null) {
                free.add(phoneEntityVos.get(i).getDeviceId());
                if (free.size() >= num) {
                    break;
                }
            }
        }
        return free;
    }

    /**
     * 远程接口手机列表
     * @return
     */
    @GetMapping("/api/list")
    public R list(HttpServletRequest request, @RequestParam Map<String, Object> params) {
        String isFlush = (String)params.get("isFlush");
        if (StringUtils.equals(isFlush,"true")) {
            this.phoneList.clear();
            Long userId = ShiroUtils.getUserId();
            if (userId == null) {
                return R.error("登录出错，请重新登录");
            }
//        Long userId = (Long) request.getAttribute(AuthorizationInterceptor.USER_KEY);
            ResponseEntity<String> results = this.restTemplate.exchange("http://dou.shciyun.com/open/common/device/list?userId=" + userId, HttpMethod.GET, null, String.class);
            String json = results.getBody();
            DevHttpJsonVo devHttpJsonVo = JSON.parseObject(json, DevHttpJsonVo.class);
            JSONObject data1 = devHttpJsonVo.getData();
            JSONArray devices = data1.getJSONArray("devices");

            List<PhoneEntityVo> phoneEntityVos = new ArrayList<>();
            devices.forEach(item -> {
                PhoneEntityVo phoneEntityVo = JSONObject.toJavaObject((JSONObject) item, PhoneEntityVo.class);
                phoneEntityVos.add(phoneEntityVo);
                phoneList.add(phoneEntityVo);
            });
            // 日期格式转化  任务名获取
            phoneList.forEach(phoneEntityVo -> {
                Date date = new Date(phoneEntityVo.getLoginTime());
                phoneEntityVo.setLoginDate(date);
                String deviceId = phoneEntityVo.getDeviceId();
                // TODO 效率太低
//                String taskName = this.warmUpService.queryNameByDeviceId(deviceId);
//                if (taskName == null) {
//                    taskName = this.accountUpService.queryNameByDeviceId(deviceId);
//                } else if (taskName == null) {
//                    taskName = this.managerWorkService.queryNameByDeviceId(deviceId);
//                } else if (taskName == null) {
//                    taskName = "";
//                }
                String taskName = "";
                phoneEntityVo.setTaskName(taskName);
            });
        }
        if (phoneList.size() == 0 || phoneList ==null) {
            return R.error("未找到设备，请核实接口数据");
        }
        int freeCount = 0;
        int onlineCount = 0;
        int[] freePhone = getFreePhone(phoneList);
        if (freePhone.length <= 1) {
            freeCount = 0;
            onlineCount = 0;
        } else {
            freeCount = freePhone[0];
            onlineCount = freePhone[1];
        }
        long page1 = Long.parseLong((String) params.get(Constant.PAGE));
        long limit = Long.parseLong((String) params.get(Constant.LIMIT));
        int i1 = (int) ((page1 - 1) * limit);
        if (i1 > phoneList.size()) {
            i1 = phoneList.size()-1;
        }
        int i = (int) (page1 * limit);
        if (i > phoneList.size()) {
            i = phoneList.size();
        }

        PageUtils page = new PageUtils(phoneList.subList(i1, i), phoneList.size(), (int) limit, (int) page1);
        return R.ok().put("page", page).put("countAll", phoneList.size()).put("freeCount", freeCount).put("onlineCount", onlineCount);
    }

    /**
     * 获取状态空闲的手机数
     */
    public int[] getFreePhone(List<PhoneEntityVo> phoneEntityVos) {
//        Long userId = ShiroUtils.getUserId();
//        ResponseEntity<String> results = this.restTemplate.exchange("http://dou.shciyun.com/open/common/device/list?userId=" + userId, HttpMethod.GET, null, String.class);
//        String json = results.getBody();
//        DevHttpJsonVo devHttpJsonVo = JSON.parseObject(json.toString(), DevHttpJsonVo.class);
//        JSONObject data1 = devHttpJsonVo.getData();
//        JSONArray devices = data1.getJSONArray("devices");

//        List<PhoneEntityVo> phoneEntityVos = new ArrayList<>();
//        devices.forEach(item -> {
//            PhoneEntityVo phoneEntityVo = JSONObject.toJavaObject((JSONObject) item, PhoneEntityVo.class);
//            phoneEntityVos.add(phoneEntityVo);
//        });
        if (phoneEntityVos == null) {
            return new int[]{};
        }
        int free = 0;
        int online = 0;
        for (int i = 0; i < phoneEntityVos.size(); i++) {
            if (phoneEntityVos.get(i).getStatus() == 1 && phoneEntityVos.get(i).getTask() == null) {
                free++;
            }
        }
        for (int i = 0; i < phoneEntityVos.size(); i++) {
            if (phoneEntityVos.get(i).getStatus() == 1) {
                online++;
            }
        }
        return new int[]{free, online};
    }

    /**
     * 通过手机编号找到手机别名
     */
//    @RequestMapping("getAliasById")
    public String getAliasById(String phoneId, Long userId) {
        ResponseEntity<String> results = this.restTemplate.exchange("http://dou.shciyun.com/open/common/device/list?userId=" + userId, HttpMethod.GET, null, String.class);
        String json = results.getBody();
        DevHttpJsonVo devHttpJsonVo = JSON.parseObject(json.toString(), DevHttpJsonVo.class);
        JSONObject data1 = devHttpJsonVo.getData();
        JSONArray devices = data1.getJSONArray("devices");
        String js = JSONObject.toJSONString(devices);

        List<PhoneEntityVo> phoneEntityVos = new ArrayList<>();
        devices.forEach(item -> {
            PhoneEntityVo phoneEntityVo = JSONObject.toJavaObject((JSONObject) item, PhoneEntityVo.class);
            phoneEntityVos.add(phoneEntityVo);
        });
        String alias = "";
        for (PhoneEntityVo phoneEntityVo : phoneEntityVos) {
            String deviceId = phoneEntityVo.getDeviceId();
            if (StringUtils.equals(deviceId, phoneId)) {
                alias = phoneEntityVo.getAlias();
            }
        }
        return alias;
    }


    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = phoneService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id) {
        PhoneEntity phone = phoneService.getById(id);

        return R.ok().put("phone", phone);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody PhoneEntity phone) {
        phoneService.save(phone);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody PhoneEntity phone) {
        phoneService.updateById(phone);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids) {
        phoneService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
